﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

internal class PostProcessXbox360Player
{
    private static string AdditionalTitleMemoryXexAttrubute()
    {
        int xboxAdditionalTitleMemorySize = PlayerSettings.xboxAdditionalTitleMemorySize;
        if ((xboxAdditionalTitleMemorySize > 0) && (EditorUserBuildSettings.xboxBuildSubtarget == XboxBuildSubtarget.Master))
        {
            UnityEngine.Debug.LogWarning("Using AdditionalTitleMemory in MASTER build. Auto-disabling");
            xboxAdditionalTitleMemorySize = 0;
        }
        return ((xboxAdditionalTitleMemorySize <= 0) ? string.Empty : ("/AdditionalTitleMemory:" + xboxAdditionalTitleMemorySize));
    }

    private static bool InstallPluginsXbox360(string pluginFolder)
    {
        string path = @"Assets\Plugins";
        if (Directory.Exists(path))
        {
            string strB = ".xex";
            string str3 = ".def";
            foreach (string str4 in Directory.GetFileSystemEntries(path))
            {
                if (string.Compare(Path.GetExtension(str4), strB, true) == 0)
                {
                    string str5 = Path.Combine(path, Path.GetFileNameWithoutExtension(str4));
                    string str6 = Path.Combine(pluginFolder, Path.GetFileNameWithoutExtension(str4));
                    string str7 = str5 + str3;
                    if (!File.Exists(str7))
                    {
                        throw new System.Exception(string.Format("Module definition file {0} not found. Required for {1}.", str7, str4));
                    }
                    if (!Directory.Exists(pluginFolder))
                    {
                        Directory.CreateDirectory(pluginFolder);
                    }
                    string to = Path.Combine(pluginFolder, Path.GetFileName(str4));
                    FileUtil.UnityFileCopy(str4, to);
                    FileUtil.UnityFileCopy(str7, str6 + str3);
                    string str9 = str5 + ".xdb";
                    if (File.Exists(str9))
                    {
                        FileUtil.UnityFileCopy(str9, str6 + ".xdb");
                    }
                    string str10 = str5 + ".pdb";
                    if (File.Exists(str10))
                    {
                        FileUtil.UnityFileCopy(str10, str6 + ".pdb");
                    }
                }
            }
        }
        return true;
    }

    private static void InstallSplashScreen(string stagingArea)
    {
        string spaPath = Path.Combine(stagingArea, "splash.xbox360");
        if (!InternalEditorUtility.Xbox360SaveSplashScreenToFile(PlayerSettings.xboxSplashScreen, spaPath))
        {
            throw new UnityException("Failed to generate splash screen.");
        }
    }

    internal static void PostProcess(BuildTarget target, BuildOptions options, string installPath, string stagingAreaData, string stagingArea, string playerPackage, string stagingAreaDataManaged)
    {
        if (Directory.Exists(installPath))
        {
            foreach (string str in Directory.GetFiles(installPath))
            {
                FileUtil.DeleteFileOrDirectory(str);
            }
        }
        else
        {
            Directory.CreateDirectory(installPath);
        }
        Thread.Sleep(100);
        string buildToolsDirectory = BuildPipeline.GetBuildToolsDirectory(target);
        string environmentVariable = Environment.GetEnvironmentVariable("XEDK");
        string str4 = FileUtil.UnityGetFileNameWithoutExtension(installPath) + ".xex";
        bool flag = EditorUserBuildSettings.xboxBuildSubtarget == XboxBuildSubtarget.Master;
        bool flag2 = (options & BuildOptions.AllowDebugging) != BuildOptions.None;
        if (environmentVariable == null)
        {
            throw new System.Exception("XEDK Environment Variable not set. Is XDK installed?");
        }
        if (flag && (PlayerSettings.strippingLevel < StrippingLevel.StripByteCode))
        {
            UnityEngine.Debug.LogWarning("Xbox 360: Code stripping should be enabled for best results.");
        }
        if (!File.Exists(Path.Combine(environmentVariable, @"bin\win32\cl.exe")))
        {
            throw new UnityException("Could not find the Xbox compiler. Is the full XDK installed?");
        }
        string[] strArray3 = new string[] { "r", "m", "d" };
        string str6 = strArray3[(int) EditorUserBuildSettings.xboxBuildSubtarget];
        string path = Path.Combine(playerPackage, string.Format("XenonPlayer_{0}.exe", str6));
        if (!File.Exists(path))
        {
            if (EditorUserBuildSettings.xboxBuildSubtarget == XboxBuildSubtarget.Debug)
            {
                throw new System.Exception("Debug player was not found. Build it from source.");
            }
            throw new System.Exception(string.Format("{0} was not found.", Path.GetFileName(path)));
        }
        bool flag3 = true;
        string str8 = !flag3 ? "raw" : "compressed";
        Process process = new Process {
            StartInfo = { FileName = Path.Combine(environmentVariable, @"bin\win32\imagexex.exe") }
        };
        object[] args = new object[] { path, str4, str8, AdditionalTitleMemoryXexAttrubute() };
        process.StartInfo.Arguments = string.Format("/nologo {3} /format:{2} /in:\"{0}\" /out:\"{1}\"", args);
        string xboxSpaFilePath = PlayerSettings.xboxSpaFilePath;
        if (!Path.IsPathRooted(xboxSpaFilePath))
        {
            xboxSpaFilePath = Path.Combine(Directory.GetCurrentDirectory(), xboxSpaFilePath);
        }
        bool flag4 = (PlayerSettings.xboxSpaFilePath.Length > 0) && File.Exists(xboxSpaFilePath);
        string xboxImageXexFilePath = PlayerSettings.xboxImageXexFilePath;
        if (!Path.IsPathRooted(xboxImageXexFilePath))
        {
            xboxImageXexFilePath = Path.Combine(Directory.GetCurrentDirectory(), xboxImageXexFilePath);
        }
        bool flag5 = (PlayerSettings.xboxImageXexFilePath.Length > 0) && File.Exists(xboxImageXexFilePath);
        if (Xbox360Utils.IsTitleIdValid(PlayerSettings.xboxTitleId))
        {
            ProcessStartInfo startInfo = process.StartInfo;
            startInfo.Arguments = startInfo.Arguments + string.Format(" /TITLEID:0x{0}", PlayerSettings.xboxTitleId);
            if (flag4)
            {
                ProcessStartInfo info2 = process.StartInfo;
                info2.Arguments = info2.Arguments + string.Format(" /section:\"{0}={1}\",RO", PlayerSettings.xboxTitleId, xboxSpaFilePath);
            }
        }
        else
        {
            UnityEngine.Debug.LogWarning("Invalid Xbox 360 title id. It will not be embedded.");
            if (flag4)
            {
                UnityEngine.Debug.LogWarning("SPA file will not be embedded due to an invalid Xbox 360 title id.");
            }
        }
        if (flag5)
        {
            ProcessStartInfo info3 = process.StartInfo;
            info3.Arguments = info3.Arguments + string.Format(" /config:\"{0}\"", xboxImageXexFilePath);
        }
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.WorkingDirectory = stagingArea;
        process.Start();
        process.WaitForExit();
        if ((process.ExitCode != 0) || !File.Exists(Path.Combine(stagingArea, str4)))
        {
            throw new System.Exception("Failed converting executable image! Args: " + process.StartInfo.Arguments);
        }
        string to = Path.Combine(stagingAreaData, "AOTCompileStep");
        FileUtil.CopyFileOrDirectory(stagingAreaDataManaged, to);
        CrossCompileOptions dynamic = CrossCompileOptions.Dynamic;
        if (!flag)
        {
            if (EditorUserBuildSettings.explicitNullChecks)
            {
                dynamic |= CrossCompileOptions.ExplicitNullChecks;
            }
            dynamic |= CrossCompileOptions.LoadSymbols;
            if (flag2)
            {
                dynamic |= CrossCompileOptions.Debugging;
            }
        }
        bool flag6 = (PlayerSettings.strippingLevel >= StrippingLevel.StripByteCode) && flag;
        if (!MonoCrossCompile.CrossCompileAOTDirectoryParallel(target, dynamic, stagingAreaDataManaged, to, PlayerSettings.aotOptions))
        {
            throw new UnityException("Cross compilation failed.");
        }
        if (!Xbox360Utils.LinkMonoAssembliesParallel(stagingAreaDataManaged, to, installPath, options))
        {
            throw new UnityException("Assembly conversion failed.");
        }
        string str12 = installPath + "/Media";
        string str13 = installPath + "/" + str4;
        FileUtil.DeleteFileOrDirectory(str13);
        FileUtil.DeleteFileOrDirectory(str12);
        FileUtil.DeleteFileOrDirectory(to);
        if (!Directory.Exists(stagingAreaData + "/Resources"))
        {
            Directory.CreateDirectory(stagingAreaData + "/Resources");
        }
        FileUtil.CopyFileOrDirectory(playerPackage + "/Data/Resources/unity default resources", stagingAreaData + "/Resources/unity default resources");
        if (flag6)
        {
            List<string> list = new List<string>();
            foreach (string str14 in Directory.GetFiles(stagingAreaDataManaged))
            {
                if (Path.GetExtension(str14) == ".dll")
                {
                    list.Add(Path.GetFileName(str14));
                }
            }
            EditorUtility.DisplayProgressBar("Building Player", "Stripping bytecode from assemblies", 0.97f);
            MonoAssemblyStripping.MonoCilStrip(target, stagingAreaDataManaged, list.ToArray());
        }
        foreach (string str15 in Directory.GetFiles(stagingAreaDataManaged))
        {
            if (Path.GetExtension(str15) == ".dll")
            {
                File.Move(str15, str15 + ".mono");
            }
        }
        string str16 = stagingAreaDataManaged + "/mono/2.0";
        if (!Directory.Exists(str16))
        {
            Directory.CreateDirectory(str16);
        }
        File.Copy(buildToolsDirectory + "/MonoXenon/etc/machine.config", str16 + "/machine.config");
        InstallPluginsXbox360(stagingAreaData + @"\Plugins");
        if (PlayerSettings.xboxSplashScreen != null)
        {
            EditorUtility.DisplayProgressBar("Building Player", "Generating splash screen", 0.98f);
            InstallSplashScreen(stagingAreaData);
        }
        Xbox360Utils.DeployKinectResources(environmentVariable, installPath);
        if ((options & BuildOptions.InstallInBuildFolder) != BuildOptions.None)
        {
            throw new System.Exception("Install in build folder is not supported.");
        }
        FileUtil.MoveFileOrDirectory(stagingAreaData, str12);
        FileUtil.MoveFileOrDirectory(Path.Combine(stagingArea, str4), str13);
        if (Directory.Exists("Assets/StreamingAssets"))
        {
            FileUtil.CopyDirectoryRecursive("Assets/StreamingAssets", str12 + "/Raw", true, true);
        }
    }
}

